package com.coffee.web;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * 压测： 300线程 1秒 循环；  tomcat cpu占用最高；
 * tomact cpu 再 70%
 * undertow cpu 再 50%
 * logback：日志耗cpu;
 */
@Aspect
@Slf4j
public class CoffeeRunTimeLogsAspect {

    @Pointcut("@annotation(com.coffee.web.CoffeeRunTimeLogs)")
    public void pointcut() {
    }

    @Around(value = "pointcut()")
    public Object operationLogController(ProceedingJoinPoint point) throws Throwable {

        long startTime = System.currentTimeMillis();
        String clsName = point.getTarget().getClass().getSimpleName();
        String methodName = point.getSignature().getName();
        log.info("=====Test===== START ====== Request[{}; {}] ========", clsName, methodName);
//        log.info("Request【{} {}】, parameter: {}.", clsName, methodName, getParam(point));
        try {
            return point.proceed();
        } finally {
            long endTime = System.currentTimeMillis();
            log.info("=====Test===== END ====== Request[{}; {}]  Total time: {} MS =======", clsName, methodName, (endTime - startTime));
        }
    }


//    private String getParam(ProceedingJoinPoint point) {
//        MethodSignature methodSignature = (MethodSignature) point.getSignature();
//        String[] parameterNames = methodSignature.getParameterNames();
//        Object[] args = point.getArgs();
//        int i = 0;
//        List<String> paramList = new ArrayList<>();
//        for (Object pojo : args) {
//            if (pojo instanceof HttpServletRequest || pojo instanceof HttpServletResponse) {
//                continue;
//            }
//            String e = parameterNames[i++] + ":" + JSON.toJSONString(pojo);
//            paramList.add(e);
//        }
//        return String.format("[%s]", String.join(",", paramList));
//    }

}
